<template>
  <div id="spaceDetailPage" class="container">
    <!-- 空间信息 -->
    <a-flex justify="space-between">
      <h2>
        <h2 v-if="space.spaceName">
          {{ space.spaceName }}（{{ SPACE_TYPE_MAP[space.spaceType] }}）
          <i class="icon-container">
            <!-- SVG 放在这里 -->
            <svg v-if="spaceLevel === SPACE_LEVEL_ENUM.PROFESSIONAL" t="1751251288079" class="icon"
                 viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="1179" width="200"
                 height="200">
              <path
                d="M929.024 466.474667l-371.754667 371.754666a64 64 0 0 1-90.538666 0l-371.754667-371.754666a64 64 0 0 1-7.978667-80.725334l138.581334-207.914666A64 64 0 0 1 278.826667 149.333333h466.346666c21.376 0 41.386667 10.666667 53.248 28.501334L936.96 385.706667a64 64 0 0 1-7.978667 80.725333z"
                fill="#d81e06" p-id="1180"></path>
              <path d="M704 362.666667l-192 256-192-256h94.805333L512 492.245333 609.194667 362.666667z" fill="#FFD6A3"
                    p-id="1181"></path>
            </svg>
            <svg v-else-if="spaceLevel === SPACE_LEVEL_ENUM.FLAGSHIP" t="1751250511758" class="icon"
                 viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="1109" width="200"
                 height="200">
              <path
                d="M929.024 466.474667l-371.754667 371.754666a64 64 0 0 1-90.538666 0l-371.754667-371.754666a64 64 0 0 1-7.978667-80.725334l138.581334-207.914666A64 64 0 0 1 278.826667 149.333333h466.346666c21.376 0 41.386667 10.666667 53.248 28.501334L936.96 385.706667a64 64 0 0 1-7.978667 80.725333z"
                fill="#333333" p-id="1110"></path>
              <path d="M704 362.666667l-192 256-192-256h94.805333L512 492.245333 609.194667 362.666667z" fill="#FFD6A3"
                    p-id="1111"></path>
            </svg>
          </i>
          <span class="version-tag">{{ spaceLevelText }}</span>
        </h2>
        <h2 v-else>
          加载中...
        </h2>

      </h2>
      <a-space size="middle">
        <a-button v-if="canUploadPicture" type="primary" @click="showModal">+ 创建图片</a-button>
        <a-button v-if="canEditPicture" :icon="h(EditOutlined)" @click="doBatchEdit"> 批量编辑</a-button>
        <a-button
          type="primary"
          ghost
          :icon="h(TeamOutlined)"
          :href="`/picture/spaceUserManage/${id}`"
          target="_blank"
          v-if="canManageSpaceUser && space.spaceType !== SPACE_TYPE_ENUM.PRIVATE"
        >
          成员管理
        </a-button>

        <a-button
          type="primary"
          ghost
          :icon="h(BarChartOutlined)"
          :href="`/picture/space_analyze?spaceId=${id}`"
          target="_blank"
        >
          空间分析
        </a-button>

        <!-- 模态框组件 -->
        <AddPictureModal
          :key="modalKey"
          v-model:model-value="addModalVisible"
          :space-id="id"
          @success="handleSuccess"
        />
        <a-tooltip
          :title="`占用空间 ${formatSize(space.totalSize)} / ${formatSize(space.maxSize)}`"
        >
          <a-progress
            type="circle"
            :percent="((space.totalSize * 100) / space.maxSize).toFixed(1)"
            :size="42"
          />
        </a-tooltip>
      </a-space>
    </a-flex>
    <!-- 搜索表单 -->
    <PictureSearchForm :onSearch="onSearch" />
    <!-- 按颜色搜索 -->
    <a-form-item label="按颜色搜索" style="margin-top: 16px">
      <ColorPicker format="hex" @pureColorChange="onColorChange" />
    </a-form-item>

    <!-- 图片列表 -->
    <PictureList :canEdit="canEditPicture"
                 :canDelete="canDeletePicture"
                 :dataList="dataList"
                 :loading="loading"
                 showOp
                 :onReload="fetchData"
    />
    <BatchEditPictureModal
      ref="batchEditPictureModalRef"
      :spaceId="id"
      :pictureList="dataList"
      :onSuccess="onBatchEditPictureSuccess"
    />

    <a-pagination
      style="text-align: right"
      v-model:current="searchParams.current"
      v-model:pageSize="searchParams.pageSize"
      :total="total"
      :show-total="() => `图片总数 ${total} / ${space.maxCount}`"
      @change="onPageChange"
    />
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref, h, watch } from 'vue'
import { getSpaceVoByIdUsingGet } from '@/api/spaceController.ts'
import { message } from 'ant-design-vue'
import { listPictureVoByPageUsingPost, searchPictureByColorUsingPost } from '@/api/pictureController.ts'
import { formatSize } from '@/utils'
import PictureList from '@/components/PictureList.vue'
import PictureSearchForm from '@/components/PictureSearchForm.vue'
import { SPACE_LEVEL_MAP, SPACE_LEVEL_ENUM } from '@/constants/space.ts'
import { ColorPicker } from 'vue3-colorpicker'
import AddPictureModal from '@/components/AddPictureModal.vue'
import BatchEditPictureModal from '@/components/BatchEditPictureModal.vue'
import { EditOutlined, BarChartOutlined, TeamOutlined } from '@ant-design/icons-vue'
import {SPACE_PERMISSION_ENUM, SPACE_TYPE_ENUM, SPACE_TYPE_MAP} from '@/constants/space-permission.ts'
// 分享弹窗引用
const batchEditPictureModalRef = ref()

// 批量编辑成功后，刷新数据
const onBatchEditPictureSuccess = () => {
  fetchData()
}
// 打开批量编辑弹窗
const doBatchEdit = () => {
  if (batchEditPictureModalRef.value) {
    batchEditPictureModalRef.value.openModal()
  }
}

// 通用权限检查函数
function createPermissionChecker(permission: string) {
  return computed(() => {
    return (space.value.permissionList ?? []).includes(permission)
  })
}

// 定义权限检查
const canManageSpaceUser = createPermissionChecker(SPACE_PERMISSION_ENUM.SPACE_USER_MANAGE)
const canUploadPicture = createPermissionChecker(SPACE_PERMISSION_ENUM.PICTURE_UPLOAD)
const canEditPicture = createPermissionChecker(SPACE_PERMISSION_ENUM.PICTURE_EDIT)
const canDeletePicture = createPermissionChecker(SPACE_PERMISSION_ENUM.PICTURE_DELETE)

const props = defineProps<{
  id: string | number
}>()
const space = ref<API.SpaceVO>({})
const spaceLevelText = computed(() => {
  return SPACE_LEVEL_MAP[space.value.spaceLevel ?? 0]
})
const spaceLevel = computed(() => {
  return space.value.spaceLevel
})
// 获取空间详情
const fetchSpaceDetail = async () => {
  try {
    const res = await getSpaceVoByIdUsingGet({
      id: props.id
    })
    if (res.data.code === 0 && res.data.data) {
      space.value = res.data.data
    } else {
      message.error('获取空间详情失败，' + res.data.message)
    }
  } catch (e: any) {
    message.error('获取空间详情失败：' + e.message)
  }
}

onMounted(() => {
  fetchSpaceDetail()
})

// 数据
const dataList = ref([])
const total = ref(0)
const loading = ref(true)

// 搜索条件
const searchParams = ref<API.PictureQueryRequestDTO>({
  current: 1,
  pageSize: 12,
  sortField: 'createTime',
  sortOrder: 'descend'
})

// 分页参数
const onPageChange = (page, pageSize) => {
  searchParams.value.current = page
  searchParams.value.pageSize = pageSize
  fetchData()
}
const onSearch = (newSearchParams: API.PictureQueryRequestDTO) => {
  searchParams.value = {
    ...searchParams.value,
    ...newSearchParams,
    current: 1
  }
  fetchData()

}

// 获取数据
const fetchData = async () => {
  loading.value = true
  // 转换搜索参数
  const params = {
    spaceId: props.id,
    ...searchParams.value
  }
  const res = await listPictureVoByPageUsingPost(params)
  if (res.data.data) {
    dataList.value = res.data.data.records ?? []
    total.value = res.data.data.total ?? 0
  } else {
    message.error('获取数据失败，' + res.data.message)
  }
  loading.value = false
}
watch(
  () => props.id,
  (newSpaceId) => {
    fetchSpaceDetail()
    fetchData()
  }
)

// 页面加载时请求一次
onMounted(() => {
  fetchData()
})

const onColorChange = async (color: string) => {
  const res = await searchPictureByColorUsingPost({
    picColor: color,
    spaceId: props.id
  })
  if (res.data.code === 0 && res.data.data) {
    const data = res.data.data ?? []
    dataList.value = data
    total.value = data.length
  } else {
    message.error('获取数据失败，' + res.data.message)
  }
}


const addModalVisible = ref(false)
const modalKey = ref(0) // 用于强制重新渲染组件
const showModal = () => {
  addModalVisible.value = true
}

const handleSuccess = () => {
  fetchData() // 刷新图片列表
}
// 可选：也可以在关闭时重置 key
watch(addModalVisible, (newVal) => {
  if (!newVal) {
    // 模态框关闭时增加 key 值
    modalKey.value += 1
  }
})
</script>

<style scoped lang="scss">
.container {
  padding: 24px;
}

.banner {
  background: linear-gradient(135deg, #4096ff, #1890ff);
  color: white;
  padding: 40px 24px;
  border-radius: 8px;
  text-align: center;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  margin-bottom: 24px;

  h1 {
    font-size: 2rem;
    margin-bottom: 12px;
  }
}

.content {
  :deep(.ant-card-head-title) {
    font-weight: bold;
  }

  .ant-statistic {
    display: inline-block;
    margin-right: 24px;
    margin-bottom: 16px;
  }
}

.version-tag {
  background-color: #ff4d4f;
  color: white;
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 12px;
  vertical-align: middle;
}

.icon-container {
  margin-right: 8px;
  display: inline-block;
  width: 24px;
  height: 24px;
  vertical-align: middle;

  .icon {
    width: 100%;
    height: 100%;
    fill: currentColor;
  }
}

:deep(.ant-image-preview-img) {
  transition: transform 0.3s ease;

  &:hover {
    transform: scale(1.05);
  }
}
</style>
